We've moved! — MindVault360 is now HexLab. Better design, more content & premium notes.

Visit HexLab →

MindVault360 has moved!

We've upgraded to HexLab — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at hexlab

Sunday, August 11, 2024

Java Encapsulation

(Tap the post to see more)


 Encapsulation

It is the process of hiding the data from the world. 

To achieve this we can use:

  • Declare class variables/attributes as private
  • Provide public get and set methods to access and update the value of a private variable.

Benefits

  • ·      Better control of class attributes and method
  •        Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • ·       Flexible: the programmer can change one part of the code without affecting other parts
  • ·       Increased security of data.
  •       Example 01:.

        //Data Hiding Getter and Setter in Java

class ShapeRectangle {

private int length, width;

//Getter Method

int getLength() {

return length;

}

int getWidth() {

return width;

}

//Setter Method

void setLength(int l) {

if (l > 0)

length = l;

else

length = 0;

}

void setWidth(int w) {

if (w > 0)

width = w;

else

width = 0;

}

int area() {

return length * width;

}

}

public class get_set {

public static void main(String args[]) {

ShapeRectangle o = new ShapeRectangle();

o.setLength(10);

o.setWidth(20);

System.out.println("Length : " + o.getLength());

System.out.println("Width : " + o.getWidth());

System.out.println("Area of Rectangle : " + o.area());

}

}

← Back Next →

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home